package cn.itcast.oa.base;

import java.lang.reflect.ParameterizedType;
import java.util.Collections;
import java.util.List;

import javax.annotation.Resource;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.transaction.annotation.Transactional;

import cn.itcast.oa.util.Page;
import cn.itcast.oa.util.QueryHelper;

@Transactional
@SuppressWarnings("unchecked")
public abstract class DaoSupportImpl<T> implements DaoSupport<T> {
    
	@Resource
	private SessionFactory sessionfoctory;
	private Class<T> clazz;
	
	
	public DaoSupportImpl(){
		//使用反射技术得到T的真实类型
		ParameterizedType pt = (ParameterizedType) this.getClass().getGenericSuperclass();//获取当前的new的对象的泛型的父类
		this.clazz=(Class<T>)pt.getActualTypeArguments()[0];//获取第一个参数类型的真是类型
		System.out.println("clazz--->"+clazz);
	
	}
	
	//拿到session
	protected Session getSession(){
		return sessionfoctory.getCurrentSession();
	}
	
	@Override
	public void save(T entity) {
		getSession().save(entity);
		
	}

	@Override
	public void delete(Long id) {
		Object obj = getById(id);
		if(obj != null){
			getSession().delete(obj);
		}
		
	}

	@Override
	public void update(T entity) {
		getSession().update(entity);
		
	}

	@Override
	public T getById(Long id) {
		if(id==null){
			return null;
		}else {
		return (T) getSession().get(clazz, id);
		}
	}

	@Override
	public List<T> getByIds(Long[] ids) {
		if(ids==null || ids.length==0){
			return Collections.EMPTY_LIST;
		}else{
		return getSession().createQuery(
				"FROM "+clazz.getSimpleName()+" WHERE id IN(:ids)")
				.setParameterList("ids", ids)
				.list();
		}
	}

	
	@Override
	public List<T> findAll() {
		
		return getSession().createQuery(
				"FROM "+clazz.getSimpleName())
				.list();
	}

	
	/**
	 * 公共的分页查询方法
	 */
	@SuppressWarnings("rawtypes")
	public Page getPage(int pageNum, int pageSize, QueryHelper queryHelper) {

		// 参数列表
		List<Object> parameters = queryHelper.getParameters();
		// 查询本页的数据列表
		Query listQuery = getSession().createQuery(queryHelper.getListQueryHql()); // 创建查询对象
		if (parameters != null) { // 设置参数
			for (int i = 0; i < parameters.size(); i++) {
				listQuery.setParameter(i, parameters.get(i));
			}
		}
		listQuery.setFirstResult((pageNum - 1) * pageSize);
		listQuery.setMaxResults(pageSize);//
		List recordList = listQuery.list(); // 执行查询
		// 查询总记录数量
		Query countQuery = getSession().createQuery(queryHelper.getCountQueryHql());
		if (parameters != null) {
			for (int i = 0; i < parameters.size(); i++) {
				countQuery.setParameter(i, parameters.get(i));
			}
		}
		Long recordCount = (Long) countQuery.uniqueResult();
		return new Page(pageNum, pageSize, recordCount.intValue(), recordList);
	}
	
}
